package com.yue.mytomcat.ex01.webcontainer;

import java.io.IOException;
import java.io.InputStream;

/**
 * 功能描述: TODO <br/>
 * 创建时间: 2016/8/2<br/>
 *
 * @author QiuYang
 */
public class Request {
    private InputStream inputStream;
    private String uri;

    public Request(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public void parse() {
        StringBuffer request = new StringBuffer(2048);
        int i;
        byte[] buffer = new byte[2048];

        try {
            i = inputStream.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
            i = -1;
        }

        for (int j = 0; j < i; j++){
            request.append((char)buffer[j]);
        }
        System.out.print(request.toString());
        uri = parseUri(request.toString());
    }

    private String parseUri(String requestStr) {
        int index1, index2;
        index1 = requestStr.indexOf(' ');       //  GET /index.html HTTP/1.1  , 获取中间的  /index.html
        if (index1 != -1){
            index2 = requestStr.indexOf(' ', index1 + 1);
            if (index2 > index1){
                return requestStr.substring(index1 + 1, index2);
            }
        }
        return null;
    }

    public String getUri(){
        return uri;
    }
}
